package org.buptsse.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.entity.HistoryItem;
import org.buptsse.entity.User;
import org.buptsse.listview.TradeUndonePage;
import org.buptsse.listview.TradedonePage;
import org.buptsse.page.MyInfoPage;
import org.buptsse.page.MyPasswordPage;
import org.buptsse.page.MyPhotoPage;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.HttpHelper;
import org.buptsse.utils.JsonUtils;

import com.google.gson.reflect.TypeToken;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

public class TradeInfoActivity extends Activity implements OnClickListener {
	/** Called when the activity is first created. */
	private static final int UnDonePage=0,DonePage=1;
	private int currentPage=UnDonePage;
	private ViewPager viewPager = null;
	private User user = null;
	private TradedonePage tradedonePage = null;
	private TradeUndonePage tradeUndonePage = null;
	
	private static final int NEW=1,FINISH=2;
	private Button backButton,refreshButton;
	private ProgressDialog pDialog;
	private boolean undoneLoaded=false,doneLoaded=false;
	
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			pDialog.dismiss();
			switch (msg.what) {
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				break;
			case APPConstant.getDealListError:
				Toast.makeText(getApplicationContext(), "未查询到相关数据", 1000).show();
				break;
			case APPConstant.getDealListFinish:
				@SuppressWarnings("unchecked")
				LinkedList<HistoryItem> list=(LinkedList<HistoryItem>) msg.obj;
				if(msg.arg1==NEW)
				{
					undoneLoaded=true;
					tradeUndonePage.FillItems(list);
				}else {
					doneLoaded=true;
					tradedonePage.FillItems(list);
				}
				break;
			}
		}
		
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ltrade_info);
		
		tradeUndonePage = new TradeUndonePage(this, user);
		tradedonePage = new TradedonePage(this, user);
		
		//刷新按钮
		refreshButton=(Button) findViewById(R.id.refresh_button);
		refreshButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showWaittingDialog("正在加载...");
				if(currentPage==UnDonePage)
				{
					//刷新为完成的交易信息
					GetDealListThread gt=new GetDealListThread(getApplicationContext(), "new");
					gt.start();
				}else {
					//刷新以完成的交易信息
					GetDealListThread gt=new GetDealListThread(getApplicationContext(), "finish");
					gt.start();
				}
			}
		});
		
		backButton = (Button) this.findViewById(R.id.bt_back);
	
		backButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				//Intent it = new Intent();
				//it.putExtra("user", user);
				//TradeInfoActivity.this.setResult(RESULT_OK, it);
				TradeInfoActivity.this.finish();
			}
		});

		final RadioGroup radioGroup = (RadioGroup) this
				.findViewById(R.id.rg_search_result_btns);
		// here is the tab to be ture
		
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.rd_undone:
					viewPager.setCurrentItem(0);
					currentPage=UnDonePage;
					if(undoneLoaded==false)
					{
						GetDealListThread gt=new GetDealListThread(getApplicationContext(), "new");
						gt.start();
					}
					break;
				case R.id.rd_done:
					viewPager.setCurrentItem(1);
					currentPage=DonePage;
					if(doneLoaded==false)
					{
						GetDealListThread gt=new GetDealListThread(getApplicationContext(), "finish");
						gt.start();
					}
					break;
				default:
					break;
				}
			}
		});

		viewPager = (ViewPager) findViewById(R.id.viewPager);
		MyPagerAdapter adapter = new MyPagerAdapter(this);
		viewPager.setAdapter(adapter);
		final RadioButton undone=(RadioButton) findViewById(R.id.rd_undone);
		final RadioButton done=(RadioButton) findViewById(R.id.rd_done);
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int page) {
				currentPage=(page==0)?UnDonePage:DonePage;
				if(currentPage==UnDonePage)
					undone.setChecked(true);
				else {
					done.setChecked(true);
				}
				if(currentPage==UnDonePage && undoneLoaded==false)
				{
					GetDealListThread gt=new GetDealListThread(getApplicationContext(), "new");
					gt.start();
				}
				else if(currentPage==DonePage && doneLoaded==false)
				{
					GetDealListThread gt=new GetDealListThread(getApplicationContext(), "finish");
					gt.start();
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		
		showWaittingDialog("正在加载...");
		GetDealListThread gt=new GetDealListThread(getApplicationContext(), "new");
		gt.start();
	}
	
	public void showWaittingDialog(String msg)
	{
		pDialog=new ProgressDialog(this);
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
	}
	
	private class GetDealListThread extends Thread
	{
		private Context context;
		private String kind;
		
		public GetDealListThread(Context context,String kind)
		{
			this.context=context;
			this.kind=kind;
		}
		
		public void run()
		{
			if(ConnectionChecker.CheckConnection(context, handler)==false)
			{
				return;
			}
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("username", GloableInstance.user.getName()));
			param.add(new BasicNameValuePair("kind", kind));
			try {
				String json=HttpHelper.sendPost(APPConstant.getDealListUrl, param);
				//System.out.println("get deal list,json:"+json+",length is:"+json.length());
				if(json.contains("nodata") || json.contains("failure"))
				{
					//失败
					//System.out.println("failure");
					Message msg=handler.obtainMessage(APPConstant.getDealListError);
					if(kind.equals("new"))
						msg.arg1=NEW;
					else 
						msg.arg1=FINISH;
					handler.sendMessage(msg);
					return;
					
				}else {
					//成功
					//System.out.println("success");
					LinkedList<HistoryItem> list=(LinkedList<HistoryItem>) JsonUtils.getJsonObject(json, new TypeToken<LinkedList<HistoryItem>>() {}.getType());
					if(list!=null)
					{
						Message msg=handler.obtainMessage(APPConstant.getDealListFinish);
						msg.obj=list;
						if(kind.equals("new"))
							msg.arg1=NEW;
						else 
							msg.arg1=FINISH;
						handler.sendMessage(msg);
						return;
					}
				}
			}
			 catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private class MyPagerAdapter extends PagerAdapter {

		private ArrayList<LinearLayout> views;

		public MyPagerAdapter(Context context) {
			views = new ArrayList<LinearLayout>();
			views.add(tradeUndonePage);
			views.add(tradedonePage);
		}

		@Override
		public void destroyItem(View view, int arg1, Object object) {
			((ViewPager) view).removeView((LinearLayout) object);
		}

		@Override
		public void finishUpdate(View arg0) {

		}

		@Override
		public int getCount() {
			return views.size();
		}

		@Override
		public Object instantiateItem(View view, int position) {
			View myView = views.get(position);
			((ViewPager) view).addView(myView);
			return myView;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

	}

	@Override
	public void onClick(View v) {
		int vid = v.getId();
		switch (vid) {

		}
	}
}